<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="100px"
    >
      <el-form-item label="品牌名" prop="name">
        <el-input v-model="dataForm.name" placeholder="品牌名"></el-input>
      </el-form-item>
      <el-form-item label="品牌logo地址" prop="productFileList">
        <!-- <el-upload
          class="upload-demo"
          drag
          :action="this.$http.adornUrl(
                '/third-party/oss/upload'
              )"
          :on-success="uploadSuccess"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div class="el-upload__tip" slot="tip">
            只能上传jpg/png文件，且不超过500kb
          </div>
        </el-upload> -->
        <!-- <uploadCommon
          ref="uploadCommon"
          :action="upload"
          :autoUpload="true"
          :productFileList.sync="dataForm.logo"
        ></uploadCommon> -->
        <el-upload
          :action="upload"
          list-type="picture-card"
          :auto-upload="true"
          :on-success="upSuccess"
          :file-list="productFileList"
          :on-preview="handlePictureCardPreview"
        >
          <i class="el-icon-plus"></i
        ></el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
        <!-- <el-input v-model="dataForm.logo" placeholder="品牌logo地址"></el-input> -->
      </el-form-item>
      <el-form-item label="介绍" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="介绍"></el-input>
      </el-form-item>
      <el-form-item label="检索首字母" prop="firstLetter">
        <el-input
          v-model="dataForm.firstLetter"
          placeholder="检索首字母"
        ></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number
          v-model="dataForm.sort"
          :min="0"
          :max="10"
          label="排序"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="状态" size="mini" prop="showStatus">
        <el-radio-group v-model="dataForm.showStatus">
          <el-radio :label="0">隐藏</el-radio>
          <el-radio :label="1">显示</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { isEmail, isMobile } from "@/utils/validate";
import uploadCommon from "../../common/upload_common";
export default {
  components: {
    uploadCommon
  },
  data() {
    var validatePassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("密码不能为空"));
      } else {
        callback();
      }
    };
    var validateComfirmPassword = (rule, value, callback) => {
      if (!this.dataForm.id && !/\S/.test(value)) {
        callback(new Error("确认密码不能为空"));
      } else if (this.dataForm.password !== value) {
        callback(new Error("确认密码与密码输入不一致"));
      } else {
        callback();
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (!isEmail(value)) {
        callback(new Error("邮箱格式错误"));
      } else {
        callback();
      }
    };
    var validateMobile = (rule, value, callback) => {
      if (!isMobile(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };
    var validateFileList = (rule, value, callback) => {
      console.log(!this.productFileList.length);
      console.log(this.productFileList.length);
      console.log(this.productFileList);
      if (this.productFileList.length <= 0) {
        callback(new Error("图片不能为空"));
      } else {
        callback();
      }
    };
    return {
      productFileList: [],
      productFileLists: "",
      dialogImageUrl: "",
      dialogVisible: false,
      upload: this.$http.adornUrl("/third-party/oss/upload"),
      visible: false,
      roleList: [],
      dataForm: {
        brandId: 0,
        name: "",
        logo: "",
        descript: "",
        showStatus: 0,
        firstLetter: "",
        sort: 0
      },
      dataRule: {
        name: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
        productFileList: [
          {
            required: true,
            message: "请上传商品图片",
            trigger: "blur",
            validator: (rule, value, callback) => {
              if (!this.productFileList.length) {
                callback(new Error("请上传商品图片"));
              } else {
                callback();
              }
            }
          }
        ],
        descript: [
          { required: true, message: "介绍不能为空", trigger: "blur" }
        ],
        firstLetter: [
          { required: true, message: "检索首字母不能为空", trigger: "blur" }
        ]
        // password: [
        //   { validator: validatePassword, trigger: 'blur' }
        // ],
        // comfirmPassword: [
        //   { validator: validateComfirmPassword, trigger: 'blur' }
        // ],
        // email: [
        //   { required: true, message: '邮箱不能为空', trigger: 'blur' },
        //   { validator: validateEmail, trigger: 'blur' }
        // ],
        // mobile: [
        //   { required: true, message: '手机号不能为空', trigger: 'blur' },
        //   { validator: validateMobile, trigger: 'blur' }
        // ]
      }
    };
  },
  methods: {
    flieUrl(file) {
      // this.flieUrls.push(file)
      console.log(file);
    },
    // uploadSuccess(res, file){
    //     console.log(res,file)
    // },
    upSuccess(res, file) {
      this.productFileList.push({
        name: file.name,
        url: res
      });
      // console.log(res, file);
    },
    handlePictureCardPreview(event, file, fileList) {
      console.log("log", event, file, fileList);
      this.dialogImageUrl = event.url;
      this.dialogVisible = true;
      console.log("this.dialogImageUrl", this.dialogImageUrl);
    },
    submit() {
      console.log("............");
    },
    init(id) {
      this.dataForm.brandId = id || 0;
      this.$http({
        url: this.$http.adornUrl("/sys/role/select"),
        method: "get",
        params: this.$http.adornParams()
      })
        .then(({ data }) => {
          this.roleList = data && data.code === 0 ? data.list : [];
        })
        .then(() => {
          this.visible = true;
          this.$nextTick(() => {
            this.$refs["dataForm"].resetFields();
          });
        })
        .then(() => {
          if (this.dataForm.brandId) {
            this.$http({
              url: this.$http.adornUrl(
                `/product/brand/info/${this.dataForm.brandId}`
              ),
              method: "get",
              params: this.$http.adornParams()
            }).then(({ data }) => {
              if (data && data.code === 0) {
                console.log(data);
                this.dataForm = { ...data.brand };
                this.productFileList = this.dataForm.logo
                  ? this.dataForm.logo.split(";").map((item, index) => {
                      return {
                        name: "图片" + index,
                        url: item
                      };
                    })
                  : [];
                console.log("productFileList", this.productFileList);
              }
            });
          }
        });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          var logo = this.productFileList.length>0
                  ? this.productFileList
                      .map((item, index) => {
                        return item.url
                          .replace("?x-oss-process=style/cm-water", "");
                      })
                      .join(";")
                  : "";
          this.$http({
            url: this.$http.adornUrl(
              `/product/brand/${!this.dataForm.brandId ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              brandId: this.dataForm.brandId || undefined,
              name: this.dataForm.name,
              logo:
                this.productFileList.length>0
                  ? this.productFileList
                      .map((item, index) => {
                        return item.url
                          .replace("?x-oss-process=style/cm-water", "");
                      })
                      .join(";")
                  : "",
              descript: this.dataForm.descript,
              showStatus: this.dataForm.showStatus,
              firstLetter: this.dataForm.firstLetter,
              sort: this.dataForm.sort
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refreshDataList");
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    }
  }
};
</script>
